//
//  RHMePlantDetailInfoVC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2025/1/3.
//

#import "RHMePlantDetailInfoVC.h"
#import "RHMePlantInfoModel.h"
#import "RHMePlantInfoDetailCell.h"
#import "RHMePlantInfoDetailSystemCell.h"
#import "RHChoiceMePlantTypeView.h"
#import "RHMeOptionTypeModel.h"
#import "RHMeSystemModel.h"
#import "RHDeviceModel.h"
#import "RHChoiceMultipleSystemVC.h"
#import "RHMultipeImagePickView.h"
#import "RHChoiceCityView.h"
#import "RHPlantModel.h"
#import "RHChoiceTimeZoneView.h"

@interface RHMePlantDetailInfoVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSArray *dataArr;

@property (nonatomic ,strong) RHMultipeImagePickView *pictureView;

@property (nonatomic ,assign) NSInteger compressIndex;//压缩图片序号

@property (nonatomic ,strong) NSMutableArray *imgUrlArr;//已经上传的图片url

@property (nonatomic ,assign) BOOL isEditPlant;//是否正在编辑

@property (nonatomic, strong) UIView *footerView;

@property (nonatomic ,strong) NSDictionary *dic;

@property (nonatomic ,strong) QMUIButton *editBtn;

@property (nonatomic ,strong) NSDictionary *addressParaDic;
@end

@implementation RHMePlantDetailInfoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    self.navigationItem.title = @"电站信息".rh_localized;
    [self createData];
    [self setupUI];
    [self getPlantDetailInfo];
    
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (self.isEdit) {
        [self modifyAction:self.editBtn];
    }
}

- (void)setupUI{
    QMUIButton *editBtn = [[QMUIButton alloc] initWithFrame:CGRectMake(0, 0,50, 40)];
    [editBtn setTitle:@"修改".rh_localized forState:UIControlStateNormal];
    editBtn.titleLabel.font = kSYSTEMFONT(14);
    [editBtn setTitleColor:CMainColorGreen forState:UIControlStateNormal];
    [editBtn setBackgroundColor:UIColor.clearColor];
    [editBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [editBtn addTarget:self action:@selector(modifyAction:) forControlEvents:UIControlEventTouchUpInside];
    self.editBtn = editBtn;
    UIBarButtonItem *rightBarBtn1 = [[UIBarButtonItem alloc] initWithCustomView:editBtn];
    self.navigationItem.rightBarButtonItem = rightBarBtn1;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:UIColor.clearColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    _tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 15)];
    _tableView.tableFooterView = self.footerView;
    [_tableView registerClass:[RHMePlantInfoDetailCell class] forCellReuseIdentifier:@"RHMePlantInfoDetailCell"];
    [_tableView registerClass:[RHMePlantInfoDetailSystemCell class] forCellReuseIdentifier:@"RHMePlantInfoDetailSystemCell"];
    [_tableView registerClass:[RHMePlantInfoDetailSystemCell class] forCellReuseIdentifier:@"RHMePlantInfoDetailDeviceCell"];
    [self.view addSubview:_tableView];
    
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    

}

#pragma mark ------- 电站详情
-(void)getPlantDetailInfo
{
    [QMUITips showLoadingInView:kAppWindow];
    NSString *url = [NSString stringWithFormat:@"%@/%ld",H_plantDetail,self.plantModel.plant_id];
    [BaseModel startGetWithCompletionAPIKey:url argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            self.dic = request.responseJSONObject[@"data"];
            NSString *imgUrl = self.dic[@"imageUrl"];
            if (ValidNullData(imgUrl).length>0) {
                NSArray *imgUrlArr = [imgUrl componentsSeparatedByString:@","];
                [self.pictureView setImageUrls:imgUrlArr];
            }
            
            [self.dataArr enumerateObjectsUsingBlock:^(RHMePlantInfoModel*  _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
                [model readInfo:self.dic];
            }];
            [self.tableView reloadData];
        }
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
        }];
}




#pragma mark ------- 编辑电站
-(void)checkPlantInfo
{
    [self.view endEditing:YES];
    self.compressIndex = 0;
    [self.imgUrlArr removeAllObjects];
    //把之前已经有的添加进去
    [self.imgUrlArr addObjectsFromArray:self.pictureView.needUploadImageUrls];
    
    BOOL checkResult = YES;
    for (RHMePlantInfoModel *model in self.dataArr) {
        if ([model.tag isEqualToString:@"plant_name"]) {
            NSString *plantName = model.content;
            if(plantName.length == 0 || (plantName.length>0&&plantName.length<4)){
                [QMUITips showError:@"电站名称请输入4至32个字符".rh_localized];
                checkResult = NO;
                break;
            }
        }
       
        if ([model.tag isEqualToString:@"plant_address"]) {
            NSString *plantAdress = model.content;
            if(plantAdress.length == 0 || (plantAdress.length>0&& (plantAdress.length<2||plantAdress.length>64))){
                [QMUITips showError:@"电站地址请输入2至64个字符".rh_localized];
                checkResult = NO;
                return;
            }
        }
       
        if ([model.tag isEqualToString:@"plant_type"]) {
            NSString *plantType = model.content;
            if(plantType.length == 0){
                [QMUITips showError:model.placeHolder];
                checkResult = NO;
                break;
            }
        }
        if ([model.tag isEqualToString:@"plant_state"]) {
            if (model.content.length == 0) {
                [QMUITips showError:model.placeHolder];
                checkResult = NO;
                break;
            }
        }
        if ([model.tag isEqualToString:@"plant_city"]) {
            if (model.content.length == 0) {
                [QMUITips showError:model.placeHolder];
                checkResult = NO;
                break;
            }
        }
   
        if (model.content.length == 0 && model.canEdit && model.isRequired) {
            [QMUITips showError:model.placeHolder];
            checkResult = NO;
            break;
        }
        
    }
    
    if (checkResult == NO) {
        self.isEditPlant = YES;
        return;
    }

    if(self.pictureView.needUploadImageArr.count == 0){
      //没有图片要上传就直接提交参数
        [self editPlantInfo];
        return;
    }else{
        [self uploadHeadImage];
    }
    
    
}

#pragma mark ----- 点击修改和确认
-(void)modifyAction:(QMUIButton*)btn
{
    NSLog(@"111--->btn width:%@",NSStringFromCGSize(btn.size));
    if (self.isEditPlant==NO) {
        self.isEditPlant = YES;
        [btn setTitle:self.isEditPlant?@"确认".rh_localized:@"修改".rh_localized forState:UIControlStateNormal];
        for (RHMePlantInfoModel *model in self.dataArr) {
            model.isEdit = YES;
        }
        [self.tableView reloadData];
        if (self.pictureView.isEditing == NO) {
            self.pictureView.isEditing = YES;
        }
        [btn sizeToFit];

        return;
    }else{
        //点击确认
        [self checkPlantInfo];
    }
   
}

-(void)updateStauts
{
    
}

#pragma mark ------ 提交参数
-(void)editPlantInfo
{
  
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:@(self.plantModel.plant_id) forKey:@"id"];
    for (RHMePlantInfoModel *model in self.dataArr) {
        if (model.canEdit) {
            if ([model.tag isEqualToString:@"plant_system"]) {//系统字段必传
                NSMutableArray *mtbArr = [NSMutableArray array];
                [model.plantSystems enumerateObjectsUsingBlock:^( RHMeSystemModel* _Nonnull systemModel, NSUInteger idx, BOOL * _Nonnull stop) {
                    [mtbArr addObject:@(systemModel.plantSystemId)];
                }];
                if (mtbArr.count>0) {
                    [para setObject:mtbArr forKey:@"systemIds"];
                }
                continue;
            }
            if ([model.tag isEqualToString:@"plant_device"]) {
                NSMutableArray *mtbArr = [NSMutableArray array];
                [model.deviceInfoList enumerateObjectsUsingBlock:^( RHDeviceModel* _Nonnull devModel, NSUInteger idx, BOOL * _Nonnull stop) {
                    [mtbArr addObject:devModel.deviceId];
                }];
                
                [para setObject:mtbArr forKey:@"deviceList"];
                
                continue;
            }
            if (model.content.length>0) {
                [para setObject:model.content forKey:model.key];
            }
          
            
        }
        
       
    }
    
    if (self.imgUrlArr.count>0) {
        
        NSString *urlStr = [self.imgUrlArr componentsJoinedByString:@","];
        [para setObject:urlStr forKey:@"imageUrl"];//图片
    }
    //地址id
    if (self.addressParaDic) {
        [para addEntriesFromDictionary:self.addressParaDic];
    }
    
    [QMUITips showLoadingInView:kAppWindow];
    [BaseModel startPutWithCompletionAPIKey:H_plantAdd argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            [QMUITips showSucceed:@"成功".rh_localized inView:self.view hideAfterDelay:1];
            if (self.modifySuccessBlock) {
                self.modifySuccessBlock();
            }
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [kNotificationCenter postNotificationName:PlantListNeedUpdateNotification object:nil];
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
    
}


#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *header = [[UIView alloc]initWithFrame:CGRectMake(15, 0, kUI_WINDOW_W-30, 0)];
    
    return header;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
   
    return nil;
   
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    kWeakSelf;
    RHMePlantInfoModel *model = self.dataArr[indexPath.row];
    if ([model.tag isEqualToString:@"plant_system"]) {
        RHMePlantInfoDetailSystemCell *systemCell = [tableView dequeueReusableCellWithIdentifier:@"RHMePlantInfoDetailSystemCell"];
        systemCell.selectBlock = ^{
            [weakSelf getSystemList:model];
        };
        systemCell.deleteBlock = ^(NSInteger index){
            [weakSelf deleteSystemFromPlant:model deviceIndex:index];
        };
        [systemCell setModel:model];
        
        return systemCell;
    }
    if ([model.tag isEqualToString:@"plant_device"]) {
        RHMePlantInfoDetailSystemCell *deviceCell = [tableView dequeueReusableCellWithIdentifier:@"RHMePlantInfoDetailDeviceCell"];
        deviceCell.selectBlock = ^{
            [weakSelf getDeviceList:model];
        };
        deviceCell.deleteBlock = ^(NSInteger index){
            [weakSelf deleteDeviceFromPlant:model deviceIndex:index];
        };
        [deviceCell setModel:model];
        
        return deviceCell;
    }
    
    RHMePlantInfoDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHMePlantInfoDetailCell"];
 
    [cell setModel:model];
    if (indexPath.row == 0) {
        [cell.bgView setTopBorder];
    }else if(indexPath.row == self.dataArr.count-1){
        [cell.bgView setBottomBorder];
    }else{
        [cell.bgView setMiddleBorder];
    }
   
    cell.clickBlock = ^{
        if ([model.tag isEqualToString:@"plant_state"]) {//选择运营状态
            [weakSelf selectPlantRunStatus:model];
        }
        if ([model.tag isEqualToString:@"plant_city"]) {//选择城市
            [weakSelf selectCity:model];
        }
        if ([model.tag isEqualToString:@"plant_zone"]) {//选择时区
            [weakSelf showTimeZoneList:model];
        }
    };
    
    return cell;
}


#pragma mark ------ 删除系统
-(void)deleteSystemFromPlant:(RHMePlantInfoModel*)infoModel  deviceIndex:(NSInteger)index
{
    
    NSMutableArray *mtbArr = [NSMutableArray arrayWithArray:infoModel.plantSystems];
    [mtbArr removeObjectAtIndex:index];
    infoModel.plantSystems = mtbArr.copy;
    [self.tableView reloadData];
}

#pragma mark ------ 删除设备
-(void)deleteDeviceFromPlant:(RHMePlantInfoModel*)infoModel  deviceIndex:(NSInteger)index
{
    
    NSMutableArray *mtbArr = [NSMutableArray arrayWithArray:infoModel.deviceInfoList];
    [mtbArr removeObjectAtIndex:index];
    infoModel.deviceInfoList = mtbArr.copy;
    [self.tableView reloadData];
}

- (UIView *)footerView{
 
    if (!_footerView) {
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,300)];
        [_footerView setBackgroundColor:UIColor.clearColor];
            
        UIView *bgView =  [[UIView alloc] initWithFrame:CGRectMake(15, 15, SCREEN_WIDTH-30,190)];
        [bgView setBackgroundColor:UIColor.whiteColor];
        bgView.layer.cornerRadius = 8;
        bgView.qmui_borderColor = kBorderColor;
        bgView.qmui_borderWidth = 1;
        bgView.qmui_borderPosition = QMUIViewBorderPositionLeft|QMUIViewBorderPositionRight|QMUIViewBorderPositionBottom|QMUIViewBorderPositionTop;
        bgView.layer.qmui_maskedCorners = QMUILayerAllCorner;
        [_footerView addSubview:bgView];
            
            
        QMUILabel *lab = [QMUILabel labelWithFont:kSYSTEMFONT(14) textColor:kCOLOR_HEX(@"3F4443")textAligment:NSTextAlignmentLeft];
        [lab setText:@"电站图片".rh_localized];
        [bgView addSubview:lab];
        [lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(15);
            make.top.mas_offset(15);
            make.right.mas_offset(-15);
        }];
            
        QMUILabel *tipLab = [QMUILabel labelWithFont:kSYSTEMFONT(10) textColor:kCOLOR_HEX(@"#8B8D92") textAligment:NSTextAlignmentLeft];
        tipLab.numberOfLines = 0;
        [tipLab setText:@"（最多可上传3张图片，格式为jpeg ,png，文件大小不超过10m）".rh_localized];
        [bgView addSubview:tipLab];
        [tipLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(15);
            make.top.equalTo(lab.mas_bottom).offset(10);
            make.right.mas_offset(-15);
        }];
            
        _pictureView = [[RHMultipeImagePickView alloc]initWithController:self];
        [bgView addSubview:_pictureView];
        [_pictureView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_offset(0);
            make.top.equalTo(tipLab.mas_bottom).offset(10);
           
        }];
        kWeakSelf;
        [RACObserve(self, isEditPlant) subscribeNext:^(id  _Nullable x) {
            BOOL isEdit = [x boolValue];
            tipLab.hidden = !isEdit;
            [weakSelf.pictureView mas_updateConstraints:^(MASConstraintMaker *make) {
               
                make.top.equalTo(tipLab.mas_bottom).offset(isEdit?10:-10);
               
            }];
            bgView.height = isEdit?190:170;
        }];
    }
    return _footerView;
}


-(void)selectCity:(RHMePlantInfoModel*)model
{
    kWeakSelf;
    RHChoiceCityView *cityView = [[RHChoiceCityView alloc]init];
    cityView.choiceResultBlock = ^(NSString * _Nonnull address,NSDictionary *paraDic) {
        model.content = address;
        weakSelf.addressParaDic = paraDic;
        [weakSelf.tableView reloadData];
    };
    [cityView showAnimation];
}

#pragma mark ----- 可添加的系统
-(void)getSystemList:(RHMePlantInfoModel*)model
{
    [QMUITips showLoadingInView:self.view];
    NSDictionary *para = @{
//                           @"userId":@([PrivateMange share].currentUser.userId),
//                           @"pageNum":@(1),
//                           @"pageSize":@(10000),
//                           @"status":@""
    };
    [RHMeSystemModel startGetWithCompletionAPIKey:H_getPlantSystemListCanAdd argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            
            NSMutableArray *arr = [NSMutableArray arrayWithArray:resultModel.data];
            //电站详情里的系统列表里用了systemId和id字段,和这里的id字段有冲突
            [arr enumerateObjectsUsingBlock:^(RHMeSystemModel*  _Nonnull systemModel, NSUInteger idx, BOOL * _Nonnull stop) {
                    systemModel.plantSystemId = systemModel.systemId;
            }];
            [self showSystemList:arr model:model];
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
       
    }];

}




#pragma mark ----- 可添加的设备
-(void)getDeviceList:(RHMePlantInfoModel*)model
{
    [QMUITips showLoadingInView:self.view];

    [RHDeviceModel startGetWithCompletionAPIKey:H_getNoAddPlantDeviceListByDeviceType argument:@{@"systemType":ValidNullData(self.plantModel.plantType)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            
            NSMutableArray *arr = [NSMutableArray arrayWithArray:resultModel.data];
           
            [self showDeviceList:arr model:model];
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
       
    }];

}


-(void)showSystemList:(NSArray*)systemList  model:(RHMePlantInfoModel*)model
{
    RHChoiceMultipleSystemVC *vc = [[RHChoiceMultipleSystemVC alloc]initWithSystemList:systemList];
    vc.curSystems = model.plantSystems;
    [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
    [vc showAnimation];
    kWeakSelf;
    vc.choiceResultBlock = ^(NSArray<RHMeSystemModel*> *arr) {
        NSMutableArray *addArr = [NSMutableArray arrayWithArray:arr];
        [addArr addObjectsFromArray:model.plantSystems];
        model.plantSystems = addArr;
        model.content = [NSString stringWithFormat:@"%ld%@",arr.count,@"个".rh_localized];
        [weakSelf.tableView reloadData];
    };
}

-(void)showDeviceList:(NSArray*)deviceList  model:(RHMePlantInfoModel*)model
{
    RHChoiceMultipleSystemVC *vc = [[RHChoiceMultipleSystemVC alloc]initWithDeviceList:deviceList];
    vc.curDevices = model.deviceInfoList;
    [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
    [vc showAnimation];
    kWeakSelf;
    vc.choiceResultBlock = ^(NSArray<RHDeviceModel*> *arr) {
        NSMutableArray *addArr = [NSMutableArray arrayWithArray:arr];
        //添加上原来已有的(这里要根据获取设备列表所调的接口来处理)
//        [model.deviceInfoList enumerateObjectsUsingBlock:^(RHDeviceModel * _Nonnull origModel, NSUInteger idx, BOOL * _Nonnull stop) {
//            __block BOOL exist = NO;
//            [arr enumerateObjectsUsingBlock:^(RHDeviceModel * _Nonnull selectModel, NSUInteger idx, BOOL * _Nonnull stop) {
//                if ([selectModel.deviceId isEqualToString:origModel.deviceId]) {
//                    exist = YES;
//                    *stop = YES;
//                }
//            }];
//            if (exist == NO) {
//                [addArr addObject:origModel];
//            }
//        }];
        
        model.deviceInfoList = addArr;
        model.content = [NSString stringWithFormat:@"%ld%@",arr.count,@"个".rh_localized];
        [weakSelf.tableView reloadData];
    };
}

#pragma mark ------ 选择时区 -------
-(void)showTimeZoneList:(RHMePlantInfoModel*)plantModel;
{
    RHChoiceTimeZoneView *choiceView = [[RHChoiceTimeZoneView alloc] init];
    choiceView.titleLab.text = @"请选择电站时区".rh_localized;
    choiceView.curTimeZone = plantModel.content;
    [choiceView scorllToCurrentValue];
    [choiceView showAnimation];
    kWeakSelf;
    choiceView.choiceResultBlock = ^(NSString * _Nonnull zone) {
        if (zone == nil) {
            return;
        }
        plantModel.content = zone;
        [weakSelf.tableView reloadData];
    };
}

-(void)selectPlantRunStatus:(RHMePlantInfoModel*)model
{
    kWeakSelf;
    
    RHChoiceMePlantTypeView *typeView = [[RHChoiceMePlantTypeView alloc]init];
    typeView.typeList = model.optionList;
    for (RHMeOptionTypeModel *typeModel in model.optionList) {
        if (typeModel.typeId == [model.content integerValue]) {
            typeView.curType = typeModel;
        }
    }
    typeView.choiceResultBlock = ^(RHMeOptionTypeModel * _Nonnull type) {
        if (type) {
            model.content = [NSString stringWithFormat:@"%ld",type.typeId];
//            weakSelf.curOperation = type;
            [weakSelf.tableView reloadData];
        }
        
    };
    [typeView showAnimation];
}







#pragma mark -------- 图片上传 ----------------
-(void)uploadHeadImage
{
    kWeakSelf;
    [QMUITips showLoading:@"压缩图片...".rh_localized inView:self.view];
    UIImage *image = self.pictureView.needUploadImageArr[self.compressIndex];
    //压缩到500K
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        UIImage *compressImg = [self compressImageQuality:image toByte:2000];
        dispatch_async(dispatch_get_main_queue(), ^{
            [QMUITips hideAllTipsInView:weakSelf.view];
          
            //上传头像
            [QMUITips showLoading:@"上传图片...".rh_localized inView:self.view];
            [BaseModel startUploadWithCompletionAPIKey:H_uploadImage rgument:@{@"file":@"ios"} image:compressImg imageName:nil requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                if(resultModel.code == 200){
                    weakSelf.compressIndex ++;
                    //保存图片参数
                    NSString *url = request.responseObject[@"url"];
                    [weakSelf.imgUrlArr addObject:ValidNullData(url)];
                    //上传完了图片
                    if (weakSelf.compressIndex == weakSelf.pictureView.needUploadImageArr.count) {
                        [weakSelf editPlantInfo];
                    }else{
                        [weakSelf uploadHeadImage];
                    }
                    
                }
            } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
               
                
            }];
        });
    });

    
}

//压缩图片质量   maxLength  单位: kb
- (UIImage *)compressImageQuality:(UIImage *)image toByte:(NSInteger)maxLength {
    
     CGFloat compression = 1;
     NSData *data = UIImageJPEGRepresentation(image, compression);
     while (data.length / 1024 > maxLength && compression > 0) {
         compression -= 0.05;
         // When compression less than a value, this code dose not work
         data = UIImageJPEGRepresentation(image, compression);
         NSLog(@"====>压缩了一次后: %ld k",(long)(data.length / 1024));
     }
     UIImage *resultImage = [UIImage imageWithData:data];
     return resultImage;
}




-(void)createData
{
    NSArray *datas = @[
        @{@"title":@"电站名称".rh_localized,
          @"placeHolder":@"请输入电站名称".rh_localized,
          @"canEdit":@(1),
          @"tag":@"plant_name",
          @"key":@"plantName"
        },
        @{@"title":@"电站类型".rh_localized,
          @"placeHolder":@"请选择电站类型".rh_localized,
          @"isSelection":@(1),
          @"optionList":@[
              @{
                  @"typeId":@(1),
                  @"typeName":@"电池储能电站"
              }
          ],
          @"tag":@"plant_type",
          @"key":@"type"
        },
        @{@"title":@"设备类型".rh_localized,
          @"placeHolder":@"请选择设备类型".rh_localized,
          @"isSelection":@(1),
          @"tag":@"device_type",
          @"key":@"plantType"
        },
        @{@"title":@"电站编码".rh_localized,
          @"placeHolder":@"请输入电站编码".rh_localized,
          @"isSelection":@(1),
          @"tag":@"plant_number",
          @"key":@"plantNumber"
        },
        @{@"title":@"投运状态".rh_localized,
          @"placeHolder":@"请选择投运状态".rh_localized,
          @"isSelection":@(1),
          @"optionList":@[
              @{
                  @"typeId":@(0),
                  @"typeName":@"待运营"
              },
              @{
                  @"typeId":@(1),
                  @"typeName":@"运营"
              },
              @{
                  @"typeId":@(2),
                  @"typeName":@"停运"
              }
          ],
          @"canEdit":@(1),
          @"tag":@"plant_state",
          @"key":@"operationStatus"
        },
        @{@"title":@"城市".rh_localized,
          @"placeHolder":@"请选择城市".rh_localized,
          @"isSelection":@(1),
          @"canEdit":@(1),
          @"tag":@"plant_city",
          @"key":@"cityName"
        },
        @{@"title":@"地址".rh_localized,
          @"placeHolder":@"请输入详细地址".rh_localized,
          @"canEdit":@(1),
          @"isRequired":@(1),
          @"tag":@"plant_address",
          @"key":@"address"
        },
        @{@"title":@"投建日期".rh_localized,
          @"placeHolder":@"请选择日期".rh_localized,
          @"isSelection":@(1),
          @"isRequired":@(1),
          @"tag":@"plant_date",
          @"key":@"constructionTime"
        },
        @{@"title":@"电站时区".rh_localized,
          @"placeHolder":@"请选择电站时区".rh_localized,
          @"isSelection":@(1),
          @"canEdit":@(1),
          @"isRequired":@(1),
          @"tag":@"plant_zone",
          @"key":@"timezone"
        },
        @{@"title":@"联系人".rh_localized,
          @"placeHolder":@"请输入联系人姓名".rh_localized,
          @"canEdit":@(1),
          @"tag":@"plant_contact_name",
          @"key":@"maintenance"
        },
        @{@"title":@"联系电话".rh_localized,
          @"placeHolder":@"请输入联系人电话".rh_localized,
          @"canEdit":@(1),
          @"tag":@"plant_contact_phone",
          @"key":@"phoneNumber"
        },
        @{@"title":@"系统数量".rh_localized,
          @"placeHolder":@"".rh_localized,
          @"tag":@"plant_system_count",
          @"key":@"systemNumber"
        },
        @{@"title":@"设备数量".rh_localized,
          @"placeHolder":@"".rh_localized,
          @"tag":@"plant_device_count",
          @"key":@"deviceNumber"
        },
        @{@"title":@"总装机容量".rh_localized,
          @"placeHolder":@"".rh_localized,
          @"unit":@"kWh",
          @"tag":@"plant_install_capacity",
          @"key":@"installedCapacity"
        },
        @{@"title":@"总装机功率".rh_localized,
          @"placeHolder":@"".rh_localized,
          @"unit":@"kW",
          @"tag":@"plant_install_power",
          @"key":@"installedPower"
        },
        @{@"title":@"所属组织".rh_localized,
          @"placeHolder":@"".rh_localized,
          @"tag":@"plant_organization",
          @"key":@"orgName"
        },
        @{@"title":@"下级系统".rh_localized,
          @"placeHolder":@"请选择系统".rh_localized,
          @"isSelection":@(1),
          @"canEdit":@(1),
          @"isRequired":@(1),
          @"tag":@"plant_system",
          @"isLast":@(1),
          @"key":@"plantSystems"
        }
    ];
    
    //户储账号没有 没有系统数量和下级系统
    if ([PrivateMange share].currentUser.operationType == OperationTypeHouse) {
        NSArray *tagArr = @[@"plant_system_count",@"plant_system"];
        NSMutableArray *arrM = [NSMutableArray array];
        [datas enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (![tagArr containsObject:obj[@"tag"]]) {
                [arrM addObject:obj];
            }
        }];
        [arrM addObject:@{@"title":@"下级设备".rh_localized,
                                 @"placeHolder":@"请选择设备".rh_localized,
                                 @"isSelection":@(1),
                                 @"canEdit":@(1),
                                 @"isRequired":@(1),
                                 @"tag":@"plant_device",
                                 @"isLast":@(1),
                                 @"key":@"deviceInfoList"
                        }];
        
        datas = arrM.copy;
    }
    //用户以上层级(管理层)
    if ([PrivateMange share].currentUser.orgType != OrganizationTypeUser) {
        NSMutableArray *arrM = [NSMutableArray arrayWithArray:datas];
        NSDictionary *user = @{@"title":@"所属用户".rh_localized,
                               @"placeHolder":@"--",
                               @"isSelection":@(1),
                               @"canEdit":@(0),
                               @"isRequired":@(0),
                               @"tag":@"plant_user",
                               @"key":@"userNickname"
        };
        [arrM insertObject:user atIndex:8];
        datas = arrM.copy;
    }
    self.dataArr = [NSArray yy_modelArrayWithClass:[RHMePlantInfoModel class] json:datas];
    
}

-(NSMutableArray *)imgUrlArr
{
    if (!_imgUrlArr) {
        _imgUrlArr = [NSMutableArray array];
    }
    return _imgUrlArr;
}
@end
